package copy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import copy.com.BaseContext;
import copy.com.R;
import copy.pojo.ShoppingCart;
import copy.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 *
 **/
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 执行完添加操作 会自动查一遍购物车 及时清除缓存
     * 添加到购物车 点击一次套餐菜品就发一次请求
     * 参数 中需要添加用户id
     * 同一条数据添加多次 需要处理该条数据的number 的字段 所以需要先查该数据是否存在
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        Set keys = redisTemplate.keys("ShoppingCart_*");
        String key = "ShoppingCart_";
        if (keys != null && keys.size() != 0) {
//            redisTemplate.delete(key);
            redisTemplate.delete(keys);
        }
        //参数传递一次请求同一用户的菜品Id和套餐Id只有一个 多条数据改变的是对应的number字段的值 SQL为
        //sel...where user_id=? and dish_id=?/setmeal_id=?;
        //1设置用户id
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setCreateTime(LocalDateTime.parse(
                "2099-04-06 12:55:22.0", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")));
        //2查询数据是菜品还是套餐 且数据是否已经存在购物车中
        LambdaQueryWrapper<ShoppingCart> sWrapper = new LambdaQueryWrapper<>();
        sWrapper.eq(ShoppingCart::getUserId, shoppingCart.getUserId());
        //2.11 要么是菜品id 要么是套餐id
        Long dishId = shoppingCart.getDishId();
        if (dishId != null) {
            //是菜品 否则是套餐
            sWrapper.eq(ShoppingCart::getDishId, dishId);
        } else {
            //2.12 套餐
            sWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        //2.2 查该条数据是否在购物车中 getone
        ShoppingCart shoppingCart1 = shoppingCartService.getOne(sWrapper);
        //3 判断是否有值 有值修改number字段加一 无值设置number字段为一
        if (shoppingCart1 != null) {
            shoppingCart1.setNumber(shoppingCart1.getNumber() + 1);
            shoppingCartService.updateById(shoppingCart1);
        } else {
            //3.2 无值则不是更新数据 是新增数据
            //数据第一次入库 设置number 为1  进入else分支 且参数中没有将number 传递过来
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            shoppingCart1 = shoppingCart;
        }
//        redisTemplate.opsForValue().set(key,JSON.toJSONString(shoppingCart1),10,TimeUnit.MINUTES);
        return R.success(shoppingCart1);
    }

    /**
     * 查看购物车
     * 根据USER_id来查询
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        //动态构造key
        String key = "ShoppingCart_1010";
        Object s = redisTemplate.opsForValue().get(key);
        if (s != null) {
            String ss = (String) s;
            List<ShoppingCart> shoppingCarts = JSON.parseObject(ss, new TypeReference<List<ShoppingCart>>() {
            });
            return R.success(shoppingCarts);
        }
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId()).orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        redisTemplate.opsForValue().set(key, JSON.toJSONString(list), 15, TimeUnit.MINUTES);
        return R.success(list);
    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> delete() {
        Set keys = redisTemplate.keys("ShoppingCart_*");
        if (keys != null && keys.size() != 0) {
            redisTemplate.delete(keys);
        }
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        shoppingCartService.remove(wrapper);
        return R.success("");
    }

    /**
     * 删除购物车数据
     * 参数 菜品id 或者套餐id
     *
     * @return
     */

/*    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart) {
        Set keys = redisTemplate.keys("ShoppingCart_*");
        if (keys != null && keys.size() != 0) {
            redisTemplate.delete(keys);
        }

        LambdaQueryWrapper<ShoppingCart> de = new LambdaQueryWrapper<>();
        de.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        if (shoppingCart.getDishId() != null) {
            de.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        }
        if (shoppingCart.getSetmealId() != null) {
            de.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        shoppingCartService.remove(de);
        return R.success("");

    }*/
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart) {
        Set keys = redisTemplate.keys("ShoppingCart_*");
        if (keys != null && keys.size() != 0) {
            redisTemplate.delete(keys);
        }
//update biao set...where user_id=? and dish_id=?/setmeal_id=?
        LambdaUpdateWrapper<ShoppingCart> de = new LambdaUpdateWrapper<>();
        de.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        if (shoppingCart.getDishId() != null) {
            //如果是菜品数量减少 判断number字段  大于1就执行更新 将number字段减去1 等于1 就调remove
            de.eq(ShoppingCart::getDishId, shoppingCart.getDishId());

            LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cartLambdaQueryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
            ShoppingCart cartServiceOne = shoppingCartService.getOne(cartLambdaQueryWrapper);
            Integer number = cartServiceOne.getNumber();
            if (number > 1) {
                de.set(ShoppingCart::getNumber, number - 1);

            }else {
                shoppingCartService.remove(de);
               /* LambdaQueryWrapper<ShoppingCart> des = new LambdaQueryWrapper<>();
                des.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
                List<ShoppingCart> list = shoppingCartService.list(des);*/
                return R.success("");
            }

        }
       else {
            de.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
            LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
            ShoppingCart one = shoppingCartService.getOne(queryWrapper);
            if (one.getNumber() > 1) {
                de.set(ShoppingCart::getNumber, one.getNumber() - 1);
            }else {
                shoppingCartService.remove(de);
                return R.success("");
            }
        }
        shoppingCartService.update(de);

        return R.success("list");

    }
}
